package com.lagou.edu.transaction;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/04
 */
@Component
public class TransactionManager {


    @Autowired
    private ConnectionUtils connectionUtils;

    //public void setConnectionUtils(ConnectionUtils connectionUtils) {
    //    this.connectionUtils = connectionUtils;
    //}

    /*private TransactionManager() {

    }

    private static TransactionManager transactionManager = new TransactionManager();

    public static TransactionManager getInstance() {
        return transactionManager;
    }*/

    /**
     * 开启事务，就是关闭自动提交，使用手动方式来控制事务提交或回滚
     * @throws SQLException
     */
    public void open() throws SQLException {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        connection.setAutoCommit(false);
    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public void commit() throws SQLException {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        connection.commit();
    }

    /**
     * 回滚事务
     * @throws SQLException
     */
    public void rollback() throws SQLException {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        connection.rollback();
    }

}
